/**
 * @Author: ls-mac
 * @Date:   2018-10-29T16:44:19+08:00
 * @Last modified by:   ls-mac
 * @Last modified time: 2018-11-07T13:53:15+08:00
 */

import { Checkbox } from 'antd';
import React, { PureComponent, Fragment } from 'react';

const CheckboxGroup = Checkbox.Group;

class CheckAllbox extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      checkedList: [],
      indeterminate: false,
      checkAll: false,
    };
  }

  onChange = checkedList => {
    const { options } = this.props;
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < options.length,
      checkAll: checkedList.length === options.length,
    });
  };

  onCheckAllChange = e => {
    const { options, form, dataIndex } = this.props;
    const { getFieldDecorator } = form;
    const checkedList = options.map(record => {
      return record.value;
    });
    const newCheckedList = e.target.checked ? checkedList : [];
    const checkObj = {};
    checkObj[dataIndex] = newCheckedList;
    console.log(checkObj);
    form.setFieldsValue(checkObj);
    this.setState({
      checkedList: newCheckedList,
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };

  render() {
    const { options, form, dataIndex } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div>
        <span>
          {getFieldDecorator(dataIndex)(
            <CheckboxGroup options={options} onChange={this.onChange} />
          )}
        </span>
        <span>
          <Checkbox
            indeterminate={this.state.indeterminate}
            onChange={this.onCheckAllChange}
            checked={this.state.checkAll}
          >
            全选
          </Checkbox>
        </span>
      </div>
    );
  }
}

export default CheckAllbox;
